<template>

    <el-row>
        <el-col>
            <el-button type="primary" @click="add_spec">添加规格</el-button>
        </el-col>
    </el-row>
    <el-form label-width="120px" >

        <el-form-item label="规格" v-for="spec,key in specification" >
            
            <el-input v-model="spec.name"></el-input>

            <el-row>
                <el-col>
                    <el-button style="margin-top:10px" type="primary" @click="add_spec_value(spec.values)">添加规格子项</el-button>
                    <el-input v-for="value,val_key in spec.values" v-model="value.name"></el-input>
                </el-col>
            </el-row>


        </el-form-item>
        
    </el-form>

    <table>
        <thead>
            <tr>
                <td v-for="item in specification">{{ item.name }}</td>

                <td>价格</td>
                <td>拼单价格</td>
                <td>库存</td>
            </tr>
        </thead>
        <template v-for="i,row in spec_combination_count">
        <tr >           
            <td v-for="item,col in specification" v-spec:td="spec_test( row, col )"  >
                <!-- {{ row }}{{ col }} -->
            </td>

            <td><input type="text" v-model="spec_price[row]"></td>
            <td><input type="text" v-model="spec_price_pindan[row]"></td>
            <td><input type="text" v-model="spec_stock[row]"></td>
        </tr>
        </template>
        
    </table>  
    <div style="height:20px"></div>
    <el-button type="primary" @click="spec_save">保存规格</el-button>
</template>

<script lang="ts" setup >

import { inject, watch, ref, computed  } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
const product:any = inject('product');
const VITE_URL = window.VITE_URL;

const spec_object:any = ref<Array<Object>>([]);
const specification:any = ref<Array<Object>>([]);
const spec_price:any = ref< Array<string> >( [] );
const spec_price_pindan:any = ref< Array<string> >( [] );
const spec_stock:any = ref< Array<number> >( [] );

// const specification = ref<Array<Object>>([]);
const status = ref<String>('0');

const spec_object2 = ref<Array<Object>>([]);

const get_spec_obj = ()=>{
    
    spec_object.value.forEach( function( obj:any ){

        var attr = obj.attr;
        var arr = attr.split(',');
        var row = 0;
        arr.forEach(function( a:any  ){

            var name = a.split(':')[0];
            var value = a.split(':')[1];


            specification.value.forEach(function( spec:any, index:any ){

                if( name == spec.name ){
                    spec.values.forEach(function( val:any, val_index:any ){

                        if( value == val.name ){
                            row += spec.row_span * val_index;
                        }

                    });
                }

            });
            
        });
        spec_price.value[row] = obj.price ;
        spec_price_pindan.value[row] = obj.price_pindan;
        spec_stock.value[row] = obj.stock;
    });
    
}    

const getSpecs = ( ) => {

    const url:string = VITE_URL + '/admin.goods/specification?goods_id=' + product.value.id;
    axios.get( url ).then( res => {

        spec_object.value = res.data.spec_object;
        specification.value = Object.values(res.data.specification);
        
        status.value = res.data.status + '';


        setTimeout(function(){
            get_spec_obj(  );
        });

        
    });

}

const add_spec = () => {

    specification.value.push({

        name:'',
        values:[]
    })
    
}

const add_spec_value = ( spec_value:any ) => {

    spec_value.push({name:''})
    
}


watch(product, (newVal, oldVal)=>{ 

    if( newVal.id ){
        getSpecs();
    }



 },{
    immediate:true
 });



 
const spec_combination_count = computed( () => {

    let count = 1;
    for( let i = 0; i < specification.value.length; i ++ ){
        count *= specification.value[i].values.length;
    }

    
    return count;

})

const spec_test = (  row:any, col:any )=>{


        let row_span:any = spec_combination_count.value;
        specification.value.forEach(function( item:any ){

            row_span = row_span / item.values.length;
            item.row_span = row_span;

            item.values.forEach(( val:any )=>{ val.name=val.name } ) // 这行纯粹是为了调用起来values数组的响应式
        });

        
        let turn_string:any =  row / specification.value[col].row_span 
        var turn:any = parseInt( turn_string.toString() );

        turn = turn % specification.value[col].values.length;
        let col_width_string:any = 100 / (specification.value.length+2 )
        return {
            turn:turn,
            col_width: parseInt( col_width_string.toString( ) ),
            col:col,
            row:row,
            spec       : specification.value[col],
            spec_value : specification.value[col].values[turn]
        };
    
}

const spec_save = ()=>{

    //todo 保存规格数据
    var spec_empty = 0;

    //todo 检测 规格名称和选项数据是否为空

    specification.value.forEach(function( item:any ){

        item.name = item.name.replace(/^(\s+)|(\s+)$/g,'');
        if( !item.name ){
            
            spec_empty = 1;
        }

        item.values.forEach(function( val_item:any ){

            val_item.name = val_item.name.replace(/^(\s+)|(\s+)$/g,'');
            if( !val_item.name ){
                
                spec_empty = 1;
            }
        });

    });

    if( spec_empty ){
        // alert('请填写商品规格名称');
        ElMessage({
            'message':'请填写商品规格名称',
            duration:1000,
            type: 'error',
        })

        return 0;
    }

    // todo 整理数据， 提交

    var spec_obj_arr = [];
    for( var row = 0; row < spec_combination_count.value; row ++ ){

        var spec_obj = {

            spec_arr:[],
            price: spec_price.value[row],
            price_pindan: spec_price_pindan.value[row],
            stock: spec_stock.value[row],

        };

        specification.value.forEach(function( item ){

            var turn = parseInt( row / item.row_span );
            turn = turn % item.values.length;
            // var spec = {
            //     name: item.name,
            //     value: item.values[turn],
            // };
            var spec = item.name + ':' + item.values[turn].name;
            spec_obj.spec_arr.push( spec );

        });

        spec_obj_arr.push( spec_obj );
    }

    // var t = this;
    // var url = this.config.web_url + '&r=goods.save_specification';
    // url += '&goods_id=' + this.goods_id ;

    const url:string = VITE_URL + '/admin.goods/save_specification?goods_id=' + product.value.id;


    var data = 'specification=' + JSON.stringify( specification.value );
    data += '&spec_obj=' + JSON.stringify( spec_obj_arr );

    axios.post( url, data ).then(function( res ){

        // if( !res.data.status ){
            // alert('商品规格参数保存成功');
        // }
        ElMessage({
            'message':res.data.status == 0 ? '商品规格参数保存成功' : res.data.message,
            duration:1000,
            type:res.data.status == 0 ? 'success' : 'error',
        })
    });
}

 const vSpec =  {
    created: function (el, binding, vnode, prevVnode) {
        var spec = binding.value.spec;
        var spec_value = binding.value.spec_value;
        el.innerHTML = spec_value.name;
        el.style.width = binding.value.col_width + '%';
    },


    updated:function( el, binding, vnode, prevVnode ){
        

        var spec = binding.value.spec;
        var spec_value = binding.value.spec_value;
        el.innerHTML = spec_value.name;
    },
    mounted(el, binding, vnode, prevVnode) { },
    beforeUpdate(el, binding, vnode, prevVnode) {
        
    },
    beforeUnmount(el, binding, vnode, prevVnode) {},
    unmounted(el, binding, vnode, prevVnode) {},
    beforeMount(el, binding, vnode, prevVnode) {},
};

watch(specification, ( newVal, oldVal ) => {

    
},{
    deep:true,
    immediate:true
})

</script>

